package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.search.dtos.UserSearchDto;
import com.heima.search.pojos.ApAssociateWords;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApAssociateWordsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {
    @Autowired
    MongoTemplate mongoTemplate;
    /**
     * 搜索联想词
     *
     * @param userSearchDto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto userSearchDto) {
        //1.参数校验
        if (userSearchDto==null|| StringUtils.isBlank(userSearchDto.getSearchWords())){
            return ResponseResult.okResult();
        }
        //分页检查
        if (userSearchDto.getPageSize()>20){
            userSearchDto.setPageSize(20);
        }
        //2.查询 模糊
        List<ApAssociateWords> associateWordsList = mongoTemplate.find(Query.query(Criteria.where("associateWords").regex(".*?\\" + userSearchDto.getSearchWords() + ".*"))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(10), ApAssociateWords.class);
        return ResponseResult.okResult(associateWordsList);
    }
}
